package com.geek.javase.ch18.videodemo.reflect.constructors;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/*
 *@Date 2025/11/5
 *@Author wangpeng
 *@Description
 * * 1. T newInstance(Object... initargs) 根据传入构造器中的形参数据，创建对象返回实例
 * 2. void setAccessible(true) “暴力破解” 设置是否取消权限检查，true取消权限检查，false表示不取消权限检查
 *
 * 如何通过Constructor来创建对象？
 * 步骤
 * 1.获取操作的类的类类型，即Class对象
 * 2.通过Class对象，获取构造器Constructor；建议使用getDeclaredConstructor(Class<?>... parameterTypes)、getDeclaredConstructors()
 * 3.通过Constructor对象的newInstance()，创建实例；若遇到私有的构造方法则需先暴力破解，即执行setAccessible(true)
 *
 */
public class ConstructorDemo2 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //1.先获取Person类类型
        Class<Person> clazz = Person.class;

        //获得匹配的构造器
        //public Person(String username, int age)
        Constructor<Person> constructor1 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println("constructor1"+constructor1);

        //private Perosn()
        Constructor<Person> constructor2 = clazz.getDeclaredConstructor();
        System.out.println("constructor2"+constructor2);

        //利用构造器，创建对象实例
        Person person1 = constructor1.newInstance( "张三", 20);
        System.out.println(person1);

        //暴力破解 取消访问权限的检查，避免抛出异常IllegalAccessException
        constructor2.setAccessible(true);

        Person person2 = constructor2.newInstance();
        person2.setUsername("李四");
        person2.setAge(20);
        System.out.println(person2);

    }
}
